package vfs.service.impl;

import java.sql.Connection;
import java.util.Iterator;
import vfs.except.VFSEntityException;
import vfs.filter.VFSFilter;
import vfs.filter.impl.VFSFilterImpl;
import vfs.obj.entity.VFSEntityFactory;
import vfs.obj.entity.VFSGroup;
import vfs.obj.entity.VFSUser;
import vfs.obj.entity.impl.VFSEntityFactoryImpl;
import vfs.service.VFSGroupService;

/**
 *
 * @author Matthew Eavenson <durandal@uga.edu>
 */
public class VFSGroupServiceImpl implements VFSGroupService{

    private VFSUser user;
    private VFSEntityFactory eFactory;
    
    public VFSGroupServiceImpl(Connection conn, VFSUser user){
        if(user == null) throw new VFSEntityException("Invalid user");
        this.user = user;
        eFactory = new VFSEntityFactoryImpl(conn);
    }
    
    @Override
    public VFSGroup getGroup(String name) {
        VFSFilter filter = new VFSFilterImpl();
        filter.addConstraint("name", name, VFSFilter.VFSFilterOperator.EQ);
        Iterator<VFSGroup> groups = getGroups(filter);
        if(groups.hasNext()) return groups.next();
        return null;
    }

    @Override
    public Iterator<VFSGroup> getGroups(VFSFilter filter) {
        return eFactory.findGroups(filter);
    }

    @Override
    public boolean exists(String name) {
        return getGroup(name) != null;
    }

    @Override
    public VFSGroup create(String name) {
        return eFactory.createGroup(name);
    }
    
    @Override
    public boolean rename(VFSGroup group, String name){
        group.setName(name);
        eFactory.storeGroup(group);
        return true;
    }

    @Override
    public boolean remove(String name) {
        VFSGroup group = getGroup(name);
        if(group != null){
            return remove(group);
        }
        return false;
    }

    @Override
    public boolean remove(VFSGroup group) {
        eFactory.removeGroup(group);
        return true;
    }
    
}
